package remato.domain.common.impl;


import java.util.HashSet;
import java.util.Set;

import remato.common.domain.impl.internal.CategoryChild;
import remato.common.domain.impl.internal.RequirementChild;
import remato.domain.common.Category;
import remato.domain.common.CategoryParentable;
import remato.domain.common.CategoryRemote;
import remato.domain.common.PropertySet;
import remato.domain.common.Requirement;

public class CategoryImpl extends CategoryParentImpl implements Category, CategoryChild {

	private Set<Requirement> requirements;
	private CategoryParentable parent;
	private Set<PropertySet> propertySets;
	private boolean hasChildren;

	public CategoryImpl() {
		super();
		requirements = new HashSet<Requirement>();
		propertySets = new HashSet<PropertySet>();
		hasChildren = false;
	}

	public Set<Requirement> getRequirements() {
		return requirements;
	}

	public void setRequirements(Set<Requirement> requirements) {
		this.requirements = requirements;
		hasChildren = false;
	}

	public boolean addRequirement(Requirement requirement) {
		if (null != requirement.getCategory() && ! requirement.getCategory().equals(this) ) {
			requirement.getCategory().removeRequirement(requirement);
		}
		boolean wasAdded = requirements.add(requirement);
		((RequirementChild)requirement).setCategory(this);
		return wasAdded;
	}

	public CategoryParentable getCategoryParent() {
		return parent;
	}

	public void setCategoryParent(CategoryParentable parent) {
		this.parent = parent;
	}

	public boolean removeRequirement(Requirement requirement) {
    	if (requirement.getCategory().equals(this)) {
    		((RequirementChild)requirement).setCategory(null);
    	}
    	return requirements.remove(requirement);
	}

	public Set<PropertySet> getPropertySets() {
		return propertySets;
	}
	
	public void setPropertySets(Set<PropertySet> propertySets) {
		this.propertySets = propertySets;
	}

	public boolean addPropertySet(PropertySet propertySet) {
		return propertySets.add(propertySet);
	}

	public boolean removePropertySet(PropertySet propertySet) {
		return propertySets.remove(propertySet);
	}
	
	@Override
	public boolean hasChildren() {
		return hasChildren || ! requirements.isEmpty() || super.hasChildren();
	}
	
	@Override
	public void setHasChildren(boolean hasChildrenValue) {
		super.setHasChildren(hasChildrenValue);
		hasChildren = hasChildrenValue;
	}

	public CategoryRemote serverCall() {
		System.out.println("Error  CategoryImpl.serverCall() should never be called!");
//		This method will actually never be executed, because the dynamic proxy should take care of it
		return null;
	}
}
